import requests
from typing import Optional, Dict
from app.core.config import settings
from app.core.logging_config import get_logger

logger = get_logger(__name__)

class WeChatAPI:
    @staticmethod
    def code2session(code: str) -> Optional[Dict]:
        """使用 code 获取用户 openid"""
        try:
            url = "https://api.weixin.qq.com/sns/jscode2session"
            params = {
                "appid": settings.WECHAT_APP_ID,
                "secret": settings.WECHAT_APP_SECRET,
                "js_code": code,
                "grant_type": "authorization_code"
            }
            
            response = requests.get(url, params=params, timeout=5)
            data = response.json()
            
            if "errcode" in data and data["errcode"] != 0:
                logger.error(f"WeChat API error: {data}")
                return None
                
            return data
            
        except Exception as e:
            logger.exception("Failed to get session from WeChat")
            return None

async def get_wechat_user_info(code: str, encrypted_data: str = None, iv: str = None):
    """
    获取微信用户信息
    """
    try:
        # 获取 session_key 和 openid
        url = "https://api.weixin.qq.com/sns/jscode2session"
        params = {
            "appid": settings.WECHAT_APP_ID,
            "secret": settings.WECHAT_APP_SECRET,
            "js_code": code,
            "grant_type": "authorization_code"
        }
        
        response = requests.get(url, params=params)
        result = response.json()
        
        if "errcode" in result:
            raise AuthenticationError(
                detail=f"微信登录失败: {result.get('errmsg', '未知错误')}"
            )
            
        return {
            "openid": result["openid"],
            "session_key": result["session_key"]
        }
        
    except Exception as e:
        raise AuthenticationError(detail=f"获取微信用户信息失败: {str(e)}")

def get_openid(code: str) -> str:
    """获取微信openid"""
    url = "https://api.weixin.qq.com/sns/jscode2session"
    params = {
        "appid": settings.WECHAT_APP_ID,
        "secret": settings.WECHAT_APP_SECRET,
        "js_code": code,
        "grant_type": "authorization_code"
    }
    
    response = requests.get(url, params=params)
    result = response.json()
    
    if "openid" not in result:
        raise ValueError(f"Failed to get openid: {result}")
        
    return result["openid"] 